package interfaces

import (
	"fmt"
	"net/http"
	"strconv"

	"github.com/gin-gonic/gin"
	"tools.hezhuyun/checker/application"
)

type Checker struct {
	fileApp   application.FileAppInterface
	folderApp application.FolderAppInterface
}

func NewChecker(fileApp application.FileAppInterface, folderApp application.FolderAppInterface) *Checker {
	return &Checker{
		fileApp:   fileApp,
		folderApp: folderApp,
	}
}

func (checker *Checker) GetFile(c *gin.Context) {
	idstr := c.Query("id")
	id, err := strconv.ParseUint(idstr, 10, 64)
	if err != nil {
		c.JSON(http.StatusOK, gin.H{
			"message": "id is not a number",
		})
		return
	}
	fileinfo, err := checker.fileApp.GetFile(id)
	if err != nil {
		c.JSON(http.StatusOK, gin.H{
			"message": "file id is not found",
		})
		return
	}
	c.JSON(http.StatusOK, gin.H{
		"message": "file info is pass",
		"data":    fileinfo,
	})
}

func (checker *Checker) GetFolder(c *gin.Context) {
	idstr := c.Query("id")
	id, err := strconv.ParseUint(idstr, 10, 64)
	if err != nil {
		c.JSON(http.StatusOK, gin.H{
			"message": "id is not a number",
		})
		return
	}
	folderInfo, err := checker.folderApp.GetFolder(id)
	if err != nil {
		c.JSON(http.StatusOK, gin.H{
			"message": fmt.Sprintf("folder %d is not found", id),
		})
		return
	}
	c.JSON(http.StatusOK, gin.H{
		"message": "folder info is pass",
		"data":    folderInfo,
	})
}

func (checker *Checker) CheckFolder(c *gin.Context) {
	folderIDStr := c.Param("folder_id")
	folderID, err := strconv.ParseUint(folderIDStr, 10, 64)
	if err != nil {
		c.JSON(http.StatusOK, gin.H{
			"message": err.Error(),
		})
		return
	}
	folder, err := checker.folderApp.GetFolder(folderID)
	if err != nil {
		c.JSON(http.StatusOK, gin.H{
			"message": fmt.Sprintf("folder %d is not found", folderID),
		})
		return
	}
	files, err := checker.fileApp.GetFilesByInnerCode(folder.InnerCode)
	fmt.Printf("files %s is not found", folder.InnerCode)
	folderAndFilesData := map[string]interface{}{
		"data": files,
	}
	c.JSON(http.StatusOK, folderAndFilesData)
}
